<?php
/**
 * Description PostingHTML
 *
 * @author Techniv
 */
class PostingHTML {
	
	/** Id of goups are allow to include HTML */
	public $groups_allow = array(5);
	
	/** Template bloc corresponding to message will be decode */
	public $bloc_apply = array('postrow', 'topic_review_row');
	/** Template var corresponding to message will be decode */
	public $var_apply = array('PREVIEW_MESSAGE');
	
	/**
	 * @Datasource
	 * @var TcnvSQL $datasouce
	 */
	private static $datasource;
	private static $table_name = "tcnvmod_htmlpost";
	
	
	/** @TplVar('ALLOW_HTML_MSG') */
	public static $tpl_check_message = "Autoriser le HTML";
	
	
	
	/** @Install */
	public function install(){
		if(defined('DEBUG')) echo "Install PostingHTML";
		
		$sql = "CREATE  TABLE IF NOT EXISTS ".self::$datasource->prefixTable(self::$table_name)." (
				post INT NOT NULL ,
				html TINYINT(1)  NULL DEFAULT 0 ,
				PRIMARY KEY (`post`))";
		
		return self::$datasource->query($sql);
	}
	
	/** 
	 * Intercept the diplaying to allow the HTML option if the member groups are
	 * autorized.
	 * @InterceptDisplay 
	 */
	public function displayAllowHTMLOption($action, $args){
		$template = $args['template'];
		$template instanceof template;
		
		if($template->filename['body'] != 'posting_body.html') return;
		
		$user_groups = TcnvMaster::getInstance()->get_user_groups();
		
		if(count($user_groups) != count(array_diff($user_groups, $this->groups_allow))){
				$template->assign_var ('POSTING_HTML', 1);
				$post_id = TcnvMaster::getInstance()->getRequestParam('p');
				$html_value = $this->get_allow_html($post_id, true);
				if($html_value){
					$html_value = " checked=\"checked\"";
				} else {
					$html_value = "";
				}
				$template->assign_var('ALLOW_HTML_VALUE', $html_value);
		}
	}
	
	/** 
	 * Launch the HTML décrypting.
	 * @InterceptBlocAssignement
	 * @InterceptVarsAssignement
	 */
	public function fire_decrypt($action,$args) {
		$message;
		$post_id;
		$form_activation = false;
		
		// Getting data
		switch ($action) {
			case InterceptBlocAssignement::$_name:
		
				$bloc = $args['block_name'];
				if(!in_array($bloc, $this->bloc_apply)) return;
				
				$message = &$args['vars']['MESSAGE'];
				$post_id = $args['vars']['POST_ID'];
				break;
				
			case InterceptVarsAssignement::$_name:
				$find = false;
				foreach ($args['vars'] as $key => &$value){
					if(in_array($key, $this->var_apply)){
						$message = &$value;
						$post_id = TcnvMaster::getInstance()->getRequestParam("p");
						$find = true;
						$form_activation = true;
						break;
					}
				}
				if(!$find) return;
				break;

			default:
				break;
		}
		
		// Check if HTML is activate for this post
		if(!$this->get_allow_html($post_id, $form_activation)) return;
		
		$this->decryptHTML($message);
	}

	/**
	 * @param int $post_id Id of post was check.
	 * @return int 1 if allow or 0;
	 */
	public function get_allow_html($post_id, $form_activation = false){
		if($form_activation && count($_POST)!=0){
			return isset($_POST['allow_html']);
		} else {
		$result = self::$datasource->query_array(
				"SELECT html FROM ".self::$datasource->prefixTable(self::$table_name).
				" WHERE post=".$post_id
		);
		
		if (count($result)==0) return 0;
		return $result[0]['html'];
		}
	}

	/**
	 * Decrypt the HTML entities to convert them in basic characters.
	 * @param string $message The message to be decrypted. It passed 
	 *		by referance for IO transaction.
	 */
	private function decryptHTML(&$message){
		
		
		$message = htmlspecialchars($message);
		$message = preg_replace("#&lt;br /&gt;#", "--jump--", $message);
		$message = preg_replace("#&amp;nbsp;#", "--space--", $message);
		
		$message = htmlspecialchars_decode($message);
		$message = htmlspecialchars_decode($message);
		
		// Encrypt the content of [code] to display the XML and HTML content correctly.
		$message = preg_replace_callback(
				"#<code>(.*)</code>#sU", 
				function($html){
					$content = $html[1];
					$content = "<pre><code>".htmlspecialchars($content)."</code></pre>";
					
					return $content;
				}, 
				$message
				);
		
		$message = preg_replace("#--jump--#", "<br />", $message);
		$message = preg_replace("#--space--#", "&nbsp;", $message);
		
		$message = preg_replace("#<script([^>]*)>([^<]*)</script>#", "== Code injection ==", $message);
		
		// Protection contre le liens et les évènements à faire
		
		$message = preg_replace("#onclick=\"([^\"]*)\"#", "", $message);
		$message = preg_replace("#onclick='([^']*)'#", "", $message);
		
	}
	
	
	/**
	 * Register the value of allow option in the database.
	 * @InterceptPosting('after');
	 */
	public function set_allow_html($action, $args) {
		$datas = $args['data'];
		$post_id = $datas['post_id'];
		$mode = $args['post_mode'];
		$html_value = (isset($_POST["allow_html"]))? 1 : 0;
		
		$table_name = self::$datasource->prefixTable(self::$table_name);
		
		$sql;
		
		if($mode == "post"){
			$sql = "INSERT INTO $table_name (post,html) "
					."VALUES ($post_id, $html_value)";
		} else {
			$sql = "SELECT * FROM $table_name "
					."WHERE post=$post_id";
			if(count(self::$datasource->query_array($sql))==0){
				$sql = "INSERT INTO $table_name (post,html) "
					."VALUES ($post_id, $html_value)";
			} else {
				$sql = "UPDATE $table_name SET html=$html_value "
						."WHERE post=$post_id";
			}
		}
		
		self::$datasource->query($sql);
	}
}
?>
